package com.mlan.userap.activity;

import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.mlan.userap.R;
import com.mlan.userap.model.ChatGroupInfo;
import com.mlan.userap.okhttp.ApiResponse;
import com.mlan.userap.okhttp.JsonCallBack;
import com.mlan.userap.okhttp.OkHttpHelper;
import com.mlan.userap.untils.Convert;
import com.mlan.userap.untils.ImageLoader;
import java.util.HashMap;
import java.util.Map;

public class ChatDetailActivity extends AppCompatActivity {
    private ChatGroupInfo groupInfo;
    private Switch switchTop;
    private boolean isUserChange = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_detail);

        String groupInfoJson = getIntent().getStringExtra("groupInfo");
        groupInfo = Convert.fromJson(groupInfoJson, ChatGroupInfo.class);

        ImageView avatar = findViewById(R.id.iv_avatar);
        TextView name = findViewById(R.id.tv_name);
        name.setText(groupInfo.getGroupName());
        ImageLoader.show(avatar, groupInfo.getGroupAvatar());

        switchTop = findViewById(R.id.switch_top);
        // 根据topSequ设置初始状态
        switchTop.setChecked(groupInfo.getTopSequ() > 0);

        switchTop.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isUserChange) return;
                setTop(isChecked);
            }
        });
    }

    private void setTop(boolean toTop) {
        Map<String, String> map = new HashMap<>();
        map.put("groupId", groupInfo.getGroupId());
        map.put("sequ", toTop ? "1" : "0");
        OkHttpHelper.get("/Chat/SetTopSequ", map, new JsonCallBack<Object>() {
            @Override
            public void onSuccess(ApiResponse<Object> result,String value2) {
                // 更新本地状态
                groupInfo.setTopSequ(toTop ? System.currentTimeMillis() : 0);
                isUserChange = false;
                switchTop.setChecked(toTop);
                isUserChange = true;
                Toast.makeText(ChatDetailActivity.this, toTop ? "已置顶" : "已取消置顶", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Exception error) {
                // 操作失败，恢复原状态
                isUserChange = false;
                switchTop.setChecked(!toTop);
                isUserChange = true;
                Toast.makeText(ChatDetailActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
} 